package com.css.dzj.dzjportal.common.util.userinfo;

import com.css.dzj.dzjportal.common.util.R;
import com.css.dzj.dzjportal.common.util.Restful.RestfulUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@Component
@PropertySource(value = "classpath:base.properties")
public class UserInfoService {
    @Value("${BASE_URL}")
    private String BASE_URL;

    @Value("${DEPT_ID}")
    private String DEPT_ID;

    @Value("${ROLE_ID_GZ}")
    private String ROLE_ID_GZ;
    @Value("${APP_CODE}")
    private String APP_CODE;

    /**
     * 根据用户编码获取用户信息
     *
     * @param userCode
     * @param request
     * @return
     */
    public boolean checkUserExist(String userCode, HttpServletRequest request) {
        String url = BASE_URL + "/platform/api/org/users/usercode/" + userCode;
        HttpMethod method = HttpMethod.GET;
        Map map = new HashMap();
        Map body = RestfulUtil.sendRestful(request, map, url, method);
        Map list = (Map) body.get("data");
        if (list != null && list.size() > 0) {
            return true;
        }
        return false;
    }

    /**
     * 新增用户
     *
     * @param request
     * @return
     */
    public Map addUser(String username, HttpServletRequest request) {
        String url = BASE_URL + "/platform/api/org/users";
        HttpMethod method = HttpMethod.POST;
        Map map = new HashMap();
        map.put("userCode", username);
        map.put("userName", username);
        Map body = (Map) RestfulUtil.sendRestful(request, map, url, method).get("data");
        return body;
    }


    /**
     * 用户设置密码
     *
     * @param password
     * @param userId
     * @param request
     * @return
     */
    public String setPassword(String password, String userId, HttpServletRequest request) {
        String url = BASE_URL + "/platform/api/org/users/" + userId + "/certification";
        HttpMethod method = HttpMethod.POST;
        Map map = new HashMap();
        map.put("cipher", password);
        map.put("appCode", APP_CODE);
        String body = (String) RestfulUtil.sendRestful(request, map, url, method).get("data");
        // Map body = (Map) RestfulUtil.sendRestflu(request, map, url, method).get("data");
        return body;
    }

    /**
     * 修改密码
    *@Author weitao
    *@Date 16:39 2020/7/21
    */
    public String updatePassword(String oldPassword ,String password, String userId, HttpServletRequest request) {
        String url = BASE_URL + "/platform/api/org/users/" + userId + "/certification";
        HttpMethod method = HttpMethod.PUT;
        Map map = new HashMap();
        map.put("oldCipher",oldPassword);
        map.put("newCipher", password);
        map.put("appCode", APP_CODE);
        String body = (String) RestfulUtil.sendRestful(request, map, url, method).get("data");
        // Map body = (Map) RestfulUtil.sendRestflu(request, map, url, method).get("data");
        return body;
    }

    /**
     * 激活用户
     *
     * @param userId
     * @param request
     * @return
     */
    public String activateUser(String userId, HttpServletRequest request) {
        String url = BASE_URL + "/platform/api/org/users/activeusers";
        HttpMethod method = HttpMethod.PATCH;
        Map map = new HashMap();
        ArrayList<String> userIds = new ArrayList<>();
        userIds.add(userId);

        /*map.put("userIds", userIds);
        String json = JSON.toJSONString(map);
        System.out.println(json);
        JSONArray jsonArray = JSONArray.parseArray(json);*/

        Object ob =  RestfulUtil.sendPatchRestful(request, userIds, url, method).get("code");
        String code=ob!=null?ob.toString():"";
        return code;
    }

    /**
     * 新增组织机构与用户关联关系
     *
     * @param userId
     * @param deptId
     * @param isMain
     * @param request
     * @return
     */
    public Map deptUserRelation(String userId, String deptId, String isMain, HttpServletRequest request) {
        String url = BASE_URL + "/platform/api/org/depts/deptUserRelation";
        HttpMethod method = HttpMethod.POST;
        Map map = new HashMap();
        map.put("deptId", deptId);
        map.put("userId", userId);
        map.put("isMain", isMain);
        Map body = (Map) RestfulUtil.sendRestful(request, map, url, method).get("data");
        return body;
    }

    /**
     * 新增角色与用户关联关系
     *
     * @param userId
     * @param request
     * @return
     * @param　roleId
     */
    public Map roleUserRelation(String userId, String roleId, HttpServletRequest request) {
        String url = BASE_URL + "/platform/api/org/roles/roleUserRelation";
        HttpMethod method = HttpMethod.POST;
        Map map = new HashMap();
        map.put("roleId", roleId);
        map.put("userId", userId);
        Map body = (Map) RestfulUtil.sendRestful(request, map, url, method).get("data");
        return body;
    }

    /**
     * 注册Base用户
     *
     * @param userCode
     * @param password
     * @param request
     * @return
     */
    public R register(String userCode, String password, String UnitType, HttpServletRequest request) {
        try {
            // 判断用户是否已存在
            boolean userExist = checkUserExist(userCode, request);
            if (userExist) {
                return R.error("用户已存在");
            }
            // 新增用户
            Map userMap = addUser(userCode, request);
            if (userMap == null || userMap.isEmpty()) {
                return R.error("base用户新增失败");
            }
            String userId = userMap.get("userId").toString();
            // 设置用户密码
            String pwdMap = setPassword(password, userId, request);
            if (pwdMap == null || StringUtils.isEmpty(pwdMap)) {
                return R.error("base用户设置密码失败");
            }
            // 用户绑定组织
            Map deptMap = deptUserRelation(userId, DEPT_ID, "1", request);
            if (deptMap == null || deptMap.isEmpty()) {
                return R.error("base用户关联组织失败");
            }
            // 角色与用户关联
            Map roleMap = roleUserRelation(userId, ROLE_ID_GZ, request);
            if (roleMap == null || roleMap.isEmpty()) {
                return R.error("base用户关联角色失败");
            }
            // 激活用户
            String code = activateUser(userId, request);
            if (StringUtils.isEmpty(code) || "500".equals(code)) {
                return R.error("base用户激活失败");
            }
            return R.ok();
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }

}
